//
//  HLIMKitSessionDataSourceImpl.m
//  YueYue
//
//  Created by hulu001 on 2024/1/11.
//

#import "HLIMKitSessionDataSourceImpl.h"
#import "HLIMKitSessionMsgDataSource.h"

@interface HLIMKitSessionDataSourceImpl ()


@property (strong, nonatomic) NIMSession *session;

@property (strong, nonatomic) id<HLIMSessionConfig> sessionConfig;

@property (strong, nonatomic) HLIMKitSessionMsgDataSource *dataSource;

@end

@implementation HLIMKitSessionDataSourceImpl


- (void)dealloc
{
}

- (instancetype)initWithSession:(NIMSession *)session sessionConfig:(nonnull id<HLIMSessionConfig>)sessionConfig
{
    self = [super init];
    
    if (self) {
        _session    =   session;
        _sessionConfig = sessionConfig;
        _dataSource =   [HLIMKitSessionMsgDataSource.alloc initWithSession:session sessionConfig:sessionConfig];
    }
    
    return self;
}

- (NSArray *)items
{
    return self.dataSource.items;
}

- (HLIMSessionMessageOperateResult *)insertMessageModels:(NSArray *)models
{
    NSArray *indexpaths = [self.dataSource insertMessageModels:models];
    HLIMSessionMessageOperateResult *result = [[HLIMSessionMessageOperateResult alloc] init];
    result.indexpaths = indexpaths;
    result.messageModels = models;
    return result;
}

- (HLIMSessionMessageOperateResult *)addMessageModels:(NSArray *)models
{
    NSArray *indexpaths = [self.dataSource appendMessageModels:models];
    HLIMSessionMessageOperateResult *result = [[HLIMSessionMessageOperateResult alloc] init];
    result.indexpaths = indexpaths;
    result.messageModels = models;
    return result;
}

- (HLIMSessionMessageOperateResult *)deleteMessageModel:(HLIMKitMessageModel *)model
{
    NSArray *indexs = [self.dataSource deleteMessageModel:model];
    HLIMSessionMessageOperateResult *result = [[HLIMSessionMessageOperateResult alloc] init];
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    for (NSNumber *index in indexs) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index.integerValue inSection:0];
        [indexPaths addObject:indexPath];
    }
    result.indexpaths    = indexPaths;
    result.messageModels = @[model];
    return result;
}

- (HLIMSessionMessageOperateResult *)updateMessageModel:(HLIMKitMessageModel *)model
{
    NSInteger index = [self.dataSource indexAtModelArray:model];
    [[self.dataSource items] replaceObjectAtIndex:index withObject:model];
    HLIMSessionMessageOperateResult *result = [[HLIMSessionMessageOperateResult alloc] init];
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:index inSection:0];
    result.indexpaths = @[indexpath];
    result.messageModels = @[model];
    return result;
}

- (void)resetMessages:(void (^)(NSError * _Nonnull))handler
{
    [self.dataSource resetMessages:handler];
}

- (NSArray *)deleteModels:(NSRange)range
{
    return [self.dataSource deleteModels:range];
}

- (NSInteger)indexAtModelArray:(HLIMKitMessageModel *)model
{
    return [self.dataSource indexAtModelArray:model];
}

- (void)sendMessageReceipt:(NSArray *)messages
{
    //找到最后一个需要发送已读回执的消息标记为已读
    for (NSInteger i = [messages count] - 1; i >= 0; i--) {
        id item = [messages objectAtIndex:i];
        NIMMessage *message = nil;
        if ([item isKindOfClass:[NIMMessage class]])
        {
            message = item;
        }
        else if ([item isKindOfClass:[HLIMKitMessageModel class]])
        {
            message = [(HLIMKitMessageModel *)item message];
        }
        if (message)
        {
            if (!message.isOutgoingMsg &&
                self.sessionConfig &&
                [self.sessionConfig respondsToSelector:@selector(shouldHandleReceiptForMessage:)] &&
                [self.sessionConfig shouldHandleReceiptForMessage:message])
            {
                
                NIMMessageReceipt *receipt = [[NIMMessageReceipt alloc] initWithMessage:message];
                
                [[[NIMSDK sharedSDK] chatManager] sendMessageReceipt:receipt
                                                          completion:^(NSError * _Nullable error) {
                    if (error) {
                    }
                }];  //忽略错误,如果失败下次再发即可
            }
        }
    }
}

- (NSDictionary *)checkReceipts:(NSArray *)receipts
{
    BOOL hasConfig = self.sessionConfig && [self.sessionConfig respondsToSelector:@selector(shouldHandleReceiptForMessage:)];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    BOOL findLastReceipt = NO;
    
    for (NSInteger i = [[self.dataSource items] count] - 1; i >= 0; i--) {
        id item = [[self.dataSource items] objectAtIndex:i];
        if ([item isKindOfClass:[HLIMKitMessageModel class]]) {
            HLIMKitMessageModel *model = (HLIMKitMessageModel *)item;
            NIMMessage *message = [model message];
            if (message.isOutgoingMsg) {
                
                if (!findLastReceipt) {
                    
                    if (message.isRemoteRead && hasConfig && [self.sessionConfig shouldHandleReceiptForMessage:message])
                    {
                        if (model.isRemoteRead) {
                            break;  //当前没有变化
                        }else{
                            dict[@(i)] = model;
                            model.isRemoteRead = YES;
                            findLastReceipt = YES;
                        }
                    }
                }
                else {
                    if (model.isRemoteRead == NO) {
                        dict[@(i)] = model;
                        model.isRemoteRead = YES;
                    } else {
                        break;//理论上只有一个已读标记在UI上,所以找到就可以跳出循环
                    }
                }
            }
        }
    }
    return dict;
}

- (HLIMKitMessageModel *)findModel:(NIMMessage *)message
{
    HLIMKitMessageModel *model;
    for (HLIMKitMessageModel *item in self.dataSource.items.reverseObjectEnumerator.allObjects) {
        if ([item isKindOfClass:[HLIMKitMessageModel class]] && [item.message.messageId isEqualToString:message.messageId]) {
            model = item;
            /// 防止那种进了会话又退出去再进来这种行为
            /// 防止SDK里回调上来的message和会话持有的message不是一个，导致刷界面刷跪了的情况
            model.message = message;
        }
    }
    return model;
}

- (void)cleanCache
{
    [self.dataSource cleanCache];
}

- (void)loadHistoryMessagesWithComplete:(nonnull void (^)(NSInteger, NSArray * _Nonnull, NSError * _Nonnull))handler {
    [self.dataSource loadHistoryMessagesWithComplete:handler];
}

- (void)loadNewMessagesWithComplete:(void (^)(NSInteger, NSArray * _Nonnull, NSError * _Nonnull))handler
{
    [self.dataSource loadNewMessagesWithComplete:handler];
}
@end

@implementation HLIMSessionMessageOperateResult

@end
